package com.mubai.web.controller.system;

import com.mubai.common.annotation.Log;
import com.mubai.common.base.Return;
import com.mubai.common.enums.BusinessType;
import com.mubai.common.exception.BusinessException;
import com.mubai.common.page.TableDataInfo;
import com.mubai.common.utils.ExcelUtil;
import com.mubai.common.utils.StringUtils;
import com.mubai.common.utils.bean.BeanUtils;
import com.mubai.files.domain.FilePlay;
import com.mubai.files.domain.Files;
import com.mubai.files.service.FilePlayService;
import com.mubai.files.service.FilesService;
import com.mubai.common.utils.file.FileUploadUtils;
import com.mubai.web.core.base.BaseController;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;

/**
 * 文件上传 信息操作处理
 *
 * @author baichuanping
 * @date 2019-01-19
 */
@Controller
@RequestMapping("/system/files")
public class SysFilesController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(SysFilesController.class);
	private String prefix = "system/files";

	@Autowired
	private FilesService filesService;
	@Autowired
	private FilePlayService filePlayService;

	@RequiresPermissions("system:files:view")
	@GetMapping()
	public String files()
	{
		return prefix + "/files";
	}

	/**listOrder
	 * 查询文件上传列表
	 */
	@RequiresPermissions("system:files:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(Files files)
	{
		startPage();
		List<Files> list = filesService.selectFilesList(files);
		return getDataTable(list);
	}
	/**
	 * 查询文件上传列表(不带显示的)
	 */
	@RequiresPermissions("system:files:list")
	@PostMapping("/listWithNoSave")
	@ResponseBody
	public TableDataInfo listWithNoSave(Files files) {
		startPage();
		List<Files> list = filesService.selectFilesListNoSave(files);
		return getDataTable(list);
	}

	/**
	 * 导出文件上传列表
	 */
	@RequiresPermissions("system:files:export")
	@PostMapping("/export")
	@ResponseBody
	public Return export(Files files)
	{
		List<Files> list = filesService.selectFilesList(files);
		ExcelUtil<Files> util = new ExcelUtil<Files>(Files.class);
		return util.exportExcel(list, "上传文件信息");
	}

	/**
	 * 新增文件上传
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap)
	{
		Files files = new Files();
		mmap.put("files", files);
		return prefix + "/add";
	}

	/**
	 * 新增保存文件上传
	 */
	@RequiresPermissions("system:files:add")
	@Log(title = "文件上传", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Return addSave(MultipartFile file,Files files) {
		int result = 0;
		Boolean isFile = false;
		try {
			files = dealFile(file, files);
			if (files.getUpdateFlag() == 1 && files.getFileId() > 0) {//修改
				if (file != null) {
					isFile = true;
				}
				result = filesService.updateFiles(files, isFile);
			} else {//新增
				result = filesService.insertFiles(files);
			}
			if (file != null && !"2".equals(files.getType())) {
				File desc = FileUploadUtils.getAbsoluteFile(FileUploadUtils.getDefaultBaseDir(), files.getUrl());
				file.transferTo(desc);
			}
		} catch (Exception e) {
			log.error("保存失败，请检查后重试！", e);
			return error(e.getMessage());
		}
		return toReturn(result);
	}
	/**
	 * 新增保存文件上传
	 */
	@RequiresPermissions("file:add")
	@Log(title = "文件上传", businessType = BusinessType.INSERT)
	@PostMapping("/addFileToShow")
	@ResponseBody
	public Return addFileToShow(String list, Long channelCode) {
		String[] ids = list.split(",");
		int result = 0;
		if (StringUtils.isEmpty(ids) || ids.length < 1) {
			throw new BusinessException("文件不能为空！");
		}
		int orderNum = 0;
		FilePlay lastModel = filePlayService.selectMaxLimit(channelCode);
		if (lastModel != null) {//取到最大的排序
			orderNum = lastModel.getOrderNum();
		}
		for (int i = 0; i < ids.length; i++) {
			Files files = filesService.selectFilesById(Long.valueOf(ids[i]));
			if (files == null) {
				throw new BusinessException("文件已被删除！");
			}
			FilePlay playsOrder = new FilePlay();
			BeanUtils.copyBeanProp(playsOrder,files);
			playsOrder.setChannelCode(channelCode);
			playsOrder.setOrderNum(orderNum++);
			result = filePlayService.insertFilePlay(playsOrder);
		}
		return toReturn(result);
	}

	private Files dealFile(MultipartFile file, Files files) throws BusinessException {
		if (file == null || "2".equals(files.getType())) return files;
		String suffix = FileUploadUtils.getSuffixName(file.getOriginalFilename());
		if (StringUtils.isEmpty(suffix)) throw new BusinessException("缺少后缀");
		String name =  FileUploadUtils.getDefaultBaseDir() + files.getFileName() + "." + suffix;
		files.setUrl(name);
		files.setSuffix(suffix);
		files.setCreateBy(getLoginName());
		files.setCreateByName(getSysUser().getUserName());
		return files;
	}
	private FilePlay getFilePlayModel(Files files, Long channelCode) {
		FilePlay filePlay = new FilePlay();
		filePlay.setChannelCode(channelCode);
		filePlay.setContent(files.getContent());
		filePlay.setFileName(files.getFileName());
		filePlay.setUrl(files.getUrl());
		filePlay.setTypes(files.getType());
		filePlay.setSuffix(files.getSuffix());
		return filePlay;
	}
	/**
	 * 修改文件上传
	 */
	@GetMapping("/edit/{fileId}")
	public String edit(@PathVariable("fileId") Long fileId, ModelMap mmap)
	{
		Files files = filesService.selectFilesById(fileId);
		mmap.put("files", files);
		String fileUrl = "/profile/" + files.getFileName() + "." + files.getSuffix();
		mmap.put("fileUrl", fileUrl);
		return prefix + "/add";
	}

	/**
	 * 修改保存文件上传
	 */
	@RequiresPermissions("system:files:edit")
	@Log(title = "文件上传", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Return editSave(Files files)
	{
		return toReturn(filesService.updateFiles(files,false));
	}

	/**
	 * 删除文件上传
	 */
	@RequiresPermissions("system:files:remove")
	@Log(title = "文件上传", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public Return remove(String ids)
	{
		return toReturn(filesService.deleteFilesByIds(ids));
	}

	@ApiOperation("获取列表")
	@RequestMapping("/listOrder")
	@ResponseBody
	public TableDataInfo getShow(FilePlay filePlay) {
		List<FilePlay> playOrderList = filePlayService.selectFilePlayList(filePlay);
		return getDataTable(playOrderList);
	}

	@RequestMapping("/listOrderPage")
	public String listOrder() {
		return prefix + "/orderShow";
	}
	/**
	 * 检验文件名是否唯一
	 * @param files
	 * @return
	 */
	@PostMapping("/checkFileNameUnqiue")
	@ResponseBody
	public String checkFileNameUnqiue(Files files) {
		return filesService.checkFileNameUnqiue(files);
	}
	@RequestMapping("/show/{id}")
	public String show(@PathVariable("id") Long id, Model model) {
		if (id != null && id > 0){
			model.addAttribute("id",id);
		}
		return prefix + "/lunbo";
	}

}